import ReactDOM from 'react-dom';
import React from 'react';
import {
	Form,
	Input,
	Button,
	Upload,
	Icon,
	TreeSelect,
	message,
	DatePicker,
	InputNumber,
} from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import wangEditor from 'wangeditor';
import BraftEditor from 'braft-editor';
import ColorPicker from 'braft-extensions/dist/color-picker';
import 'braft-editor/dist/index.css';
import 'braft-extensions/dist/color-picker.css';
import _ from 'lodash';
import { plateData, plateToZh } from 'utils/common';
import moment from 'moment';

const { Item } = Form;

BraftEditor.use(
	ColorPicker({
		includeEditors: ['editor-with-color-picker'],
		// theme: 'light' // 支持dark和light两种主题，默认为dark
	})
);

const labelLayout = {
	labelCol: {
		md: { span: 6 },
		xl: { span: 2 },
	},
	wrapperCol: {
		md: { span: 12 },
		xl: { span: 12 },
	},
};
const btnLayout = {
	wrapperCol: {
		md: { span: 12, offset: 12 },
		xl: { span: 12, offset: 2 },
	},
};
const { TextArea } = Input;

class GraphicForm extends React.PureComponent {
	constructor() {
		super();
		this.state = {
			editorState: BraftEditor.createEditorState(
				'<p>编辑器内的样式可能与数据中心详情展示有一定出入,请酌情调整...</p>'
			),
			pic_num: 1,
			fileList: [],
			uid: -1,
			title: plateData[0].children[0].value,
		};
	}
	componentDidMount() {
		const { action, dispatch } = this.props;
		// const editor = new wangEditor(ReactDOM.findDOMNode(this._div));
		// // editor.customConfig.uploadImgShowBase64 = true;
		// editor.customConfig.customUploadImg = function(files, insert) {
		// 	files &&
		// 		files.length > 0 &&
		// 		files.map(file => {
		// 			const payload = new FormData();
		// 			payload.append('file', file);
		// 			payload.append('appName', 'dev');
		// 			dispatch({
		// 				type: 'graphic/upload',
		// 				payload,
		// 				callback: url => {
		// 					insert(url);
		// 				},
		// 			});
		// 		});
		// 	const payload = new FormData();
		// 	// payload.append('file',)
		// };
		// editor.customConfig.zIndex = 10;
		// editor.create();
		// action === 'view' && editor.$textElem.attr('contenteditable', 'false');
		// this.setState({
		// 	editor,
		// });

		if (action !== 'post') {
			const { dispatch } = this.props;
			const { pathname } = window.location;
			const id = pathname.split('/')[2];
			const _this = this;
			dispatch({
				type: 'graphic/detail',
				payload: {
					id,
				},
				callback: data => {
					if (action === 'edit') {
						document.getElementById('subtitle').value = data.subtitle;
						document.getElementById('introduce').value = data.introduce || '';
					}

					let fileList = [];
					const { coverImg, title, plateType, englishTitle } = data;
					const coverImg_split = coverImg ? coverImg.split(',') : [];
					coverImg_split.map((item, index) => {
						item &&
							fileList.push({
								uid: -(index + 1),
								status: 'done',
								url: item,
							});
					});
					_this.setState({
						fileList,
						title,
						parent: plateType,
						englishTitle,
						editorState: BraftEditor.createEditorState(data.content),
						pic_num: fileList.length,
					});
				},
			});
		}
	}
	handleChange = editorState => {
		this.setState({
			editorState: editorState,
			// outputHTML: editorState.toHTML(),
		});
	};
	onRemove = file => {
		const { fileList } = this.state;
		const new_fileList = _.cloneDeep(fileList);
		_.remove(new_fileList, function(n) {
			return n.uid === file.uid;
		});
		return true;
	};
	customRequest = ({ file }) => {
		const _this = this;
		const { dispatch } = _this.props;
		const { fileList, title, uid } = _this.state;
		const new_fileList = _.cloneDeep(fileList);

		const payload = new FormData();
		payload.append('file', file);
		payload.append('appName', 'dev');

		dispatch({
			type: 'graphic/upload',
			payload,
			callback: res => {
				const type = file.type.split('/')[0];
				let status = 'done';
				if (title === 'scenedisplay_video') {
					if (type !== 'video') {
						message.error('请上传视频!');
						status = 'error';
					}
				} else {
					if (type !== 'image') {
						message.error('请上传图片!');
						status = 'error';
					}
				}
				new_fileList.push({
					uid: uid - 1,
					url: res,
					status,
					type: file.type,
				});
				_this.setState({
					fileList: new_fileList,
					uid: uid - 1,
				});
			},
		});
	};
	onSubmit = e => {
		e.preventDefault();
		const _this = this;
		const { form, action, detail, dispatch } = _this.props;
		const { editorState, title, parent, englishTitle, fileList, pic_num } = _this.state;
		form.validateFields((err, values) => {
			const subtitle = document.getElementById('subtitle').value;
			const introduce = document.getElementById('introduce').value;
			if (!subtitle) return message.error('标题不能为空!');
			if (!title) return message.error('板块不能为空!');
			if (fileList.length === 0) return message.error('封面不能为空!');
			if (fileList.length !== pic_num) return message.error(`应上传${pic_num}张封面!`);
			let coverImg = '';
			fileList &&
				fileList.length > 0 &&
				fileList.map(item => {
					coverImg += `${item.url},`;
				});

			const payload = {
				plateType: parent,
				title,
				englishTitle,
				coverImg,
				content: editorState.toHTML(),
				isDisplay: 1,
				subtitle,
				introduce,
				createDate: values.createDate,
				sort: values.sort,
			};

			if (action === 'post') {
				dispatch({
					type: 'graphic/add',
					payload,
					callback: () => {
						message.success('上传成功!');
						router.push('/graphic');
					},
				});
			}

			if (action === 'edit') {
				dispatch({
					type: 'graphic/update',
					payload: {
						...payload,
						id: detail.id,
					},
					callback: () => {
						message.success('已更新!');
						router.push('/graphic');
					},
				});
			}
		});
	};
	onChange = (value, node, extra) => {
		const { fileList } = this.state;
		const {
			triggerNode: {
				props: { title, parent, englishTitle },
			},
		} = extra;
		const pic_num = parent === 'convenientlife' || parent === 'socialgovernance' ? 3 : 1;
		if (value === 'scenedisplay_video') message.warning('当前板块的封面需要上传视频，请注意!');
		this.setState({
			pic_num,
			title: value,
			parent,
			englishTitle,
			fileList:
				value !== 'scenedisplay_video'
					? pic_num === 1
						? (fileList.length > 0 && [fileList[0]]) || []
						: fileList
					: [],
		});
	};
	uploadChange = ({ fileList }) => {
		this.setState({
			fileList,
		});
	};
	subtitleChange = e => {};
	//富文本文件上传
	handleUploadFile = param => {
		const serverURL = '/upload';
		const xhr = new XMLHttpRequest();
		const fd = new FormData();

		// libraryId可用于通过mediaLibrary示例来操作对应的媒体内容
		console.log(param.libraryId);

		const successFn = response => {
			// 假设服务端直接返回文件上传后的地址
			// 上传成功后调用param.success并传入上传后的文件地址
			param.success({
				url: JSON.parse(xhr.responseText).data,
			});
		};

		const progressFn = event => {
			// 上传进度发生变化时调用param.progress
			param.progress((event.loaded / event.total) * 100);
		};

		const errorFn = response => {
			// 上传发生错误时调用param.error
			param.error({
				msg: 'unable to upload.',
			});
		};

		xhr.upload.addEventListener('progress', progressFn, false);
		xhr.addEventListener('load', successFn, false);
		xhr.addEventListener('error', errorFn, false);
		xhr.addEventListener('abort', errorFn, false);

		fd.append('file', param.file);
		// fd.append('appName', appName);
		xhr.open('POST', serverURL, true);
		xhr.send(fd);
	};
	render() {
		const {
			form: { getFieldDecorator },
			action,
			detail,
		} = this.props;
		const { fileList, editorState, pic_num, title } = this.state;
		const required = action === 'view' ? false : true;
		return (
			<Form onSubmit={this.onSubmit} style={{ margin: '20px 0' }}>
				<Item
					label={`${title === '党员风采' ? '党员姓名' : '标题'}`}
					{...labelLayout}
					required={required}
				>
					{action !== 'view' ? (
						// <>
						// 	{getFieldDecorator('subtitle', {
						// 		rules: [{ required: true, message: '标题不能为空!' }],
						// 		// initialValue: action === 'edit' ? detail && detail.title : '',
						// 	})(<Input />)}
						// </>
						<Input id="subtitle" />
					) : (
						<p>{(detail && detail.subtitle) || '无'}</p>
					)}
				</Item>
				<Item label="板块" {...labelLayout} required={required}>
					{action !== 'view' ? (
						<>
							{getFieldDecorator('sector', {
								rules: [{ required: true, message: '请选择板块!' }],
								initialValue:
									action === 'edit'
										? detail && detail.title
										: plateData[0].children[0].value,
							})(
								<TreeSelect
									style={{ width: 400 }}
									onChange={this.onChange}
									treeData={plateData}
									dropdownStyle={{ maxHeight: 600, overflow: 'auto' }}
									placeholder="请选择板块..."
									disabled={action === 'edit' ? true : false}
								/>
							)}
						</>
					) : (
						<p>{(detail && plateToZh[detail.title]) || '无'}</p>
					)}
				</Item>
				<Item label="图文实际时间" {...labelLayout}>
					{action !== 'view' ? (
						<>
							{getFieldDecorator('createDate', {
								rules: [{ required: true, message: '请选择实际时间!' }],
								initialValue:
									action === 'edit'
										? detail && moment(detail.createDate)
										: moment(),
							})(<DatePicker format="YYYY-MM-DD" />)}
						</>
					) : (
						<p>
							{(detail && moment(detail.createDate)).format('YYYY-MM-DD') ||
								moment().format('YYYY-MM-DD')}
						</p>
					)}
				</Item>
				<Item label="排列顺序" {...labelLayout}>
					{action !== 'view' ? (
						<>
							{getFieldDecorator('sort', {
								// rules: [{ required: true, message: '标题不能为空!' }],
								initialValue: action === 'edit' ? detail && detail.sort : 1,
							})(<InputNumber />)}
						</>
					) : (
						<p>{(detail && detail.sort) || '1'}</p>
					)}
				</Item>
				<Item
					label={`上传${(title === '二维码' && title) ||
						(title === '视频风貌' && '视频') ||
						'封面'}`}
					{...labelLayout}
					required={required}
				>
					{action !== 'view' ? (
						<>
							{/* {getFieldDecorator('coverImg', {
								rules: [{ required: true, message: '请上传封面!' }],
								getValueFromEvent: this.cuscomRequest,
								initialValue: action === 'edit' ? detail && detail.img : '',
							})( */}
							<Upload
								// action="//jsonplaceholder.typicode.com/posts/"
								listType="picture-card"
								fileList={fileList}
								onChange={this.uploadChange}
								customRequest={this.customRequest}
								onRemove={this.onRemove}
							>
								{fileList.length >= pic_num ? null : (
									<div>
										<Icon type={this.state.loading ? 'loading' : 'plus'} />
										<div className="ant-upload-text">Upload</div>
									</div>
								)}
							</Upload>
							{/* )} */}
						</>
					) : (
						<>
							{fileList &&
								fileList.length > 0 &&
								fileList.map(item => (
									<div
										key={item.uid}
										style={{
											width: 320,
											height: 320,
											overFlow: 'hidden',
											margin: '20px 0',
											display: 'inline-block',
										}}
									>
										{title !== 'scenedisplay_video' ? (
											<img src={item.url} style={{ width: '100%' }} />
										) : (
											<video
												src={item.url}
												style={{ width: '100%' }}
												controls
											/>
										)}
									</div>
								))}
						</>
					)}
				</Item>
				<Item label={`简介`} {...labelLayout} required={required}>
					{action !== 'view' ? (
						// <>
						// 	{getFieldDecorator('subtitle', {
						// 		rules: [{ required: true, message: '标题不能为空!' }],
						// 		// initialValue: action === 'edit' ? detail && detail.title : '',
						// 	})(<Input />)}
						// </>
						<TextArea id="introduce" />
					) : (
						<p>{(detail && detail.introduce) || '无'}</p>
					)}
				</Item>
				<Item label="图文详情" {...labelLayout}>
					{/* <div ref={ref => (this._div = ref)}>
						{editor &&
							editor.txt.html(
								(action !== 'post' && detail && detail.content) ||
									'<p>编辑器内的样式可能与数据中心详情展示有一定出入,请酌情调整...</p>'
							)}
					</div> */}
					<div>
						{action === 'edit' ? (
							<BraftEditor
								id="editor-with-color-picker"
								value={editorState}
								style={{ border: '1px solid #d9d9d9' }}
								onChange={this.handleChange}
								height={400}
								contentFormat={'html'}
								excludeControls={['emoji']}
								media={{
									allowPasteImage: true,
									image: true,
									video: true,
									uploadFn: this.handleUploadFile,
								}}
							/>
						) : (
							<div dangerouslySetInnerHTML={{ __html: editorState.toHTML() }} />
						)}
					</div>
				</Item>
				<Item {...btnLayout}>
					{action !== 'view' && (
						<Button type="primary" style={{ marginRight: 10 }} htmlType="submit">
							{action === 'post' ? '发布' : '更新'}
						</Button>
					)}
					<Button type="danger" onClick={() => router.push('/graphic')}>
						{action === 'view' ? '返回' : '取消'}
					</Button>
				</Item>
			</Form>
		);
	}
}

export default Form.create()(
	connect(state => ({
		detail: state.graphic.detail,
	}))(GraphicForm)
);
